package com.xiaoxi.bms.service.common.fastdfs.impl;

import com.xiaoxi.bms.common.constant.enumeration.statuscode.system.FileSystemEnums;
import com.xiaoxi.bms.common.exception.BMSException;
import com.xiaoxi.bms.common.util.FastDfsUtils;
import com.xiaoxi.bms.domain.common.FastDfs;
import com.xiaoxi.bms.service.common.fastdfs.FastDfsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author xiaoxi
 * @ProjectName springcloudbms
 * @PackageName com.xiaoxi.fastdfs.service.impl
 * @ClassName FastDfsServiceImpl
 * @Description TODO
 * @Date 2023/2/9 18:55
 * @Version 1.0
 */
@Service
@Slf4j
public class FastDfsServiceImpl implements FastDfsService {

    @Value("${fastdfs.url}")
    private String url;

    /**
     * 图片
     */
    private static final String IMAGES = "images";

    /**
     * 表格
     */
    private static final String EXCELS = "excels";

    @Override
    public FastDfs uploadImage(MultipartFile file) throws BMSException {

        if (file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
            throw new BMSException(FileSystemEnums.FILE_IS_NULL);
        }

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        if (!".jpg".equals(suffix) && !".png".equals(suffix) && !".jpeg".equals(suffix)) {
            throw new BMSException(FileSystemEnums.PLEASE_CHECK_FILE_FORMAT);
        }

        log.info("uploadImage - url : {}", url);

        return FastDfsUtils.upload(file, suffix, IMAGES, url);
    }


    @Override
    public FastDfs uploadExcel(MultipartFile file) throws BMSException {

        if (file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
            throw new BMSException(FileSystemEnums.FILE_IS_NULL);
        }

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        if (!".xls".equals(suffix) && !".xlsx".equals(suffix) && !".csv".equals(suffix)) {
            throw new BMSException(FileSystemEnums.PLEASE_CHECK_FILE_FORMAT);
        }

        log.info("uploadExcel - url : {}", url);

        return FastDfsUtils.upload(file, suffix, EXCELS, url);
    }



}

